<script setup lang="ts">
import { ref, watch } from 'vue'
import { UserInfo } from 'common'
import { useRootStore } from '../stores/root'
import { storeToRefs } from 'pinia'
import { updateUserProfile, setCookie } from '../api'

interface Props {
  modelValue: boolean
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'showMessage', message: string): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

const rootStore = useRootStore()
const { userInfo, Cookie } = storeToRefs(rootStore)

// 表单数据
const formData = ref({
  name: '',
  avatar: ''
})

// 错误信息
const errors = ref({
  name: ''
})

// 加载状态
const loading = ref(false)

// 监听弹窗显示状态，初始化表单数据
watch(() => props.modelValue, (newVal) => {
  console.log('UserProfileDialog modelValue 变化:', newVal)
  if (newVal && userInfo.value) {
    console.log('初始化表单数据:', userInfo.value)
    formData.value = {
      name: userInfo.value.name||"",
      avatar: userInfo.value.avatar
    }
    errors.value = { name: '' }
  }
})

// 验证表单
const validateForm = () => {
  errors.value = { name: '' }
  let isValid = true

  if (!formData.value.name.trim()) {
    errors.value.name = '用户名不能为空'
    isValid = false
  } else if (formData.value.name.length < 2) {
    errors.value.name = '用户名至少2个字符'
    isValid = false
  }

  return isValid
}

// 上传头像
const uploadAvatar = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.style.display = 'none'
  
  input.onchange = (event) => {
    const file = (event.target as HTMLInputElement).files?.[0]
    if (file) {
      const reader = new FileReader()
      reader.onload = (e) => {
        formData.value.avatar = e.target?.result as string
      }
      reader.readAsDataURL(file)
    }
  }
  
  document.body.appendChild(input)
  input.click()
  document.body.removeChild(input)
}

// 保存用户信息
const saveUserInfo = async () => {
  if (!validateForm()) {
    return
  }

  loading.value = true
  
  try {
    // 设置cookie并调用后端API更新用户信息
    setCookie(Cookie.value)
    const response = await updateUserProfile(formData.value.name, formData.value.avatar)
    
    if (response.data.code === 200) {
      // 更新store中的用户信息
      if (userInfo.value) {
        const updatedUserInfo: UserInfo = {
          ...userInfo.value,
          name: formData.value.name,
          avatar: formData.value.avatar
        }
        rootStore.updateUserInfo(updatedUserInfo)
      }
      
      // 显示成功提示
      emit('showMessage', '用户信息更新成功！')
      
      // 关闭弹窗
      emit('update:modelValue', false)
    } else {
      console.error('保存用户信息失败:', response.data.msg)
      emit('showMessage', response.data.msg || '保存失败，请重试')
    }
  } catch (error) {
    console.error('保存用户信息失败:', error)
    emit('showMessage', '网络错误，请重试')
  } finally {
    loading.value = false
  }
}

// 关闭弹窗
const closeDialog = () => {
  emit('update:modelValue', false)
}
</script>

<template>
  <v-dialog 
    :model-value="modelValue" 
    @update:model-value="(value: boolean) => emit('update:modelValue', value)"
    max-width="500px" 
    persistent
    attach="body"
  >
    <v-card>
      <v-card-title class="text-h6">
        <v-icon icon="mdi-account-edit" class="mr-2"></v-icon>
        编辑个人信息
      </v-card-title>
      
      <v-card-text>
        <v-form @submit.prevent="saveUserInfo">
          <!-- 头像上传 -->
          <div class="text-center mb-4">
            <v-avatar 
              :image="formData.avatar" 
              size="100" 
              class="mb-2"
              style="cursor: pointer;"
              @click="uploadAvatar"
            >
              <v-icon icon="mdi-camera" size="30"></v-icon>
            </v-avatar>
            <div class="text-caption text-grey">
              点击头像更换
            </div>
          </div>
          
          <!-- 用户名输入 -->
          <v-text-field
            v-model="formData.name"
            label="用户名"
            variant="outlined"
            :error-messages="errors.name"
            :disabled="loading"
            required
          ></v-text-field>
        </v-form>
      </v-card-text>
      
      <v-card-actions class="pa-4">
        <v-spacer></v-spacer>
        <v-btn 
          variant="text" 
          @click="closeDialog"
          :disabled="loading"
        >
          取消
        </v-btn>
        <v-btn 
          color="primary" 
          @click="saveUserInfo"
          :loading="loading"
          :disabled="formData.name.trim()"
        >
          保存
        </v-btn>
      </v-card-actions>
    </v-card>
  </v-dialog>
</template>

<style scoped>
.v-avatar {
  transition: transform 0.2s ease;
}

.v-avatar:hover {
  transform: scale(1.05);
}
</style> 